const connect = require("../model");
const md5 = require("md5")
const config = require("../config")
var jwt = require('jsonwebtoken');
const register = {
    async add(req, res) {
        let { name, password, code } = req.body

        // 先判断一下使用有该用户名
        let sql = "select * from userinfo where name =?"
        let [data] = await connect.query(sql, [name])
        if (data.length >= 1) {
            res.json({ code: 40003, message: "用户名已被占用" })
        } else {
            let sql = `INSERT into userinfo(name,password) VALUES(?,?)`
            await connect.query(sql, [name, md5(password + config.prived)])
            res.json({ code: 2000, message: "注册成功" })
        }

    },
    async login(req, res) {
        let { name, password } = req.body

        let sql = `select a.* ,JSON_ARRAYAGG(JSON_OBJECT('name', d.name , 'role',d.role )) as role 
        from userinfo as a   
        LEFT JOIN user_role  as b  on a.id =b.userid 
        LEFT JOIN role as d  on b.roleid = d.id  
        where a.name = ? and a.password = ?  
        GROUP BY a.id`
        let [data] = await connect.query(sql, [name, md5(password + config.prived)])
        console.log(data);
        if (data.length > 0) {
            let userinfo = data[0]
            let token = jwt.sign(userinfo, config.prived, { expiresIn: '24h' })
            res.json({
                code: 2000,
                message: "登录成功",
                token: token,
                userinfo: userinfo,

            })
        } else {
            res.json({
                code: 40004,
                message: "账号密码错误"
            })
        }

    }
}


module.exports = register